package com.dianxun.exam.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.dianxun.exam.MainApplication;
import com.dianxun.exam.R;
import com.dianxun.exam.adapter.ExamAdapter;
import com.dianxun.exam.common.AppConfig;
import com.dianxun.exam.common.AppKeyManager;
import com.dianxun.exam.common.base.BaseActivity;
import com.dianxun.exam.entity.AnswerBean;
import com.dianxun.exam.entity.AnswerBeanDao;
import com.dianxun.exam.entity.AnswerChoiceListBean;
import com.dianxun.exam.entity.AnswerItemListBean;
import com.dianxun.exam.entity.AnswerJudgmentListBean;
import com.dianxun.exam.entity.ChoiceListBean;
import com.dianxun.exam.entity.DaoSession;
import com.dianxun.exam.entity.ItemListBean;
import com.dianxun.exam.entity.JudgmentListBean;
import com.dianxun.exam.entity.SubjectChoiceListBean;
import com.dianxun.exam.entity.SubjectItemListBean;
import com.dianxun.exam.entity.SubjectJudgmentListBean;
import com.dianxun.exam.entity.TempSaveBean;
import com.dianxun.exam.entity.TempSaveBeanDao;
import com.dianxun.exam.entity.TikuBean;
import com.dianxun.exam.entity.TikuBeanDao;
import com.dianxun.exam.entity.TitleEntity;
import com.dianxun.exam.entity.TypeEntity;
import com.dianxun.exam.ui.widget.WaitDialog;
import com.dianxun.exam.utils.RxKeyboardTool;
import com.dianxun.exam.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 正在考试
 */
public class ExamActivity extends BaseActivity implements View.OnClickListener {

    public static final String EXTRA_TIKUID = "tikuid";
    @BindView(R.id.tv_back)
    TextView tv_back;
    @BindView(R.id.list_paper)
    RecyclerView list_paper;
    @BindView(R.id.tv_left_time)
    TextView tv_left_time;
    private ExamAdapter adapter;
    private DaoSession daoSession;
    private TikuBeanDao tikuBeanDao;
    private AnswerBeanDao answerBeanDao;
    private TempSaveBeanDao tempSaveBeanDao;
    private TikuBean tikuBean;
    private TempSaveBean tempSaveBean;
    private long startTime;
    private long endTime;
    private List<TempSaveBean> tempSaveBeanList;
    private WaitDialog mWaitDialog;
    private android.os.CountDownTimer timer;

    @Override
    protected int getContentView() {
        return R.layout.activity_exam;
    }

    @Override
    protected void initView() {
        mWaitDialog = new WaitDialog(self);
        mWaitDialog.setMessage("保存暂存中，请稍等。。。");
        mWaitDialog.setCancelable(false);

        daoSession = ((MainApplication) getApplication()).getDaoSession();
        answerBeanDao = daoSession.getAnswerBeanDao();
        tikuBeanDao = daoSession.getTikuBeanDao();
        // 清除题库缓存
        tikuBeanDao.detachAll();
        tempSaveBeanDao = daoSession.getTempSaveBeanDao();
        List<TikuBean> tikuBeanList = tikuBeanDao.queryBuilder()
                .where(TikuBeanDao.Properties.TikuId.eq(getIntent().getExtras().getString(EXTRA_TIKUID)))
                .list();
        tikuBean = tikuBeanList.get(0);

        list_paper.setLayoutManager(new LinearLayoutManager(self));
        list_paper.setNestedScrollingEnabled(false);
        list_paper.setItemViewCacheSize(1000);

        List<TypeEntity> datas = new ArrayList<>();

        tempSaveBeanList = tempSaveBeanDao.queryBuilder()
                .where(TempSaveBeanDao.Properties.TikuId.eq(tikuBean.getTikuId()),
                        TempSaveBeanDao.Properties.UserId.eq(AppConfig.getInstance().getUserId()))
                .orderAsc(TempSaveBeanDao.Properties.LeftTime)
                .list();

        if (tempSaveBeanList.size() > 0) {
            tempSaveBean = tempSaveBeanList.get(0);
            startTime = tempSaveBean.getStartTime();
            countDown(tv_left_time, tempSaveBean.getLeftTime() * 1000, 1000);
            if (tikuBean.getJudgmentList().size() > 0) {
                TitleEntity judgmentTitle = new TitleEntity("判断题");
                judgmentTitle.setItemType(AppKeyManager.TYPE_TITLE);
                datas.add(judgmentTitle);

                for (int i = 0; i < tikuBean.getJudgmentList().size(); i++) {
                    JudgmentListBean judgmentListBean = tikuBean.getJudgmentList().get(i);
                    judgmentListBean.setItemType(AppKeyManager.TYPE_JUDGMENT);
                    AnswerJudgmentListBean answerJudgmentListBean = tempSaveBean.getJudgmentList().get(i);
                    judgmentListBean.setAnswer(answerJudgmentListBean.getAnswer());
                    datas.add(judgmentListBean);
                }
            }

            if (tikuBean.getChoice0List().size() > 0) {
                TitleEntity singleChoiceTitle = new TitleEntity("单选题");
                singleChoiceTitle.setItemType(AppKeyManager.TYPE_TITLE);
                datas.add(singleChoiceTitle);

                for (int i = 0; i < tikuBean.getChoice0List().size(); i++) {
                    ChoiceListBean choiceListBean = tikuBean.getChoice0List().get(i);
                    choiceListBean.setItemType(AppKeyManager.TYPE_SINGLE_CHOICE);
                    for (int j = 0; j < choiceListBean.getItemList().size(); j++) {
                        choiceListBean.getItemList().get(j).setAnswer(tempSaveBean.getChoiceList().get(i).getItemList().get(j).getAnswer());
                    }
                    datas.add(choiceListBean);
                }
            }

            if (tikuBean.getChoice1List().size() > 0) {
                TitleEntity multipleChoiceTitle = new TitleEntity("多选题");
                multipleChoiceTitle.setItemType(AppKeyManager.TYPE_TITLE);
                datas.add(multipleChoiceTitle);

                for (int i = 0; i < tikuBean.getChoice1List().size(); i++) {
                    ChoiceListBean choiceListBean = tikuBean.getChoice1List().get(i);
                    choiceListBean.setItemType(AppKeyManager.TYPE_MULTIPLE_CHOICE);
                    for (int j = 0; j < choiceListBean.getItemList().size(); j++) {
                        choiceListBean.getItemList().get(j).setAnswer(tempSaveBean.getChoiceList()
                                .get(i + tikuBean.getChoice0List().size()).getItemList().get(j).getAnswer());
                    }
                    datas.add(choiceListBean);
                }
            }
        } else {
            startTime = Utils.getCurTimeMills();
            countDown(tv_left_time, tikuBean.getTotalTime() * 60 * 1000, 1000);
            if (tikuBean.getJudgmentList().size() > 0) {
                TitleEntity judgmentTitle = new TitleEntity("判断题");
                judgmentTitle.setItemType(AppKeyManager.TYPE_TITLE);
                datas.add(judgmentTitle);

                for (JudgmentListBean judgmentListBean : tikuBean.getJudgmentList()) {
                    judgmentListBean.setItemType(AppKeyManager.TYPE_JUDGMENT);
                    datas.add(judgmentListBean);
                }
            }

            if (tikuBean.getChoice0List().size() > 0) {
                TitleEntity singleChoiceTitle = new TitleEntity("单选题");
                singleChoiceTitle.setItemType(AppKeyManager.TYPE_TITLE);
                datas.add(singleChoiceTitle);

                for (ChoiceListBean choiceListBean : tikuBean.getChoice0List()) {
                    choiceListBean.setItemType(AppKeyManager.TYPE_SINGLE_CHOICE);
                    datas.add(choiceListBean);
                }
            }

            if (tikuBean.getChoice1List().size() > 0) {
                TitleEntity multipleChoiceTitle = new TitleEntity("多选题");
                multipleChoiceTitle.setItemType(AppKeyManager.TYPE_TITLE);
                datas.add(multipleChoiceTitle);

                for (ChoiceListBean choiceListBean : tikuBean.getChoice1List()) {
                    choiceListBean.setItemType(AppKeyManager.TYPE_MULTIPLE_CHOICE);
                    datas.add(choiceListBean);
                }
            }
        }

        adapter = new ExamAdapter(datas);
        adapter.setHasStableIds(true);

        View headerView = getLayoutInflater().inflate(R.layout.item_exam_header, (ViewGroup) list_paper.getParent(), false);
        TextView tv_paper_no = headerView.findViewById(R.id.tv_paper_no);
        TextView tv_paper_name = headerView.findViewById(R.id.tv_paper_name);
        TextView tv_time = headerView.findViewById(R.id.tv_time);
        TextView tv_score = headerView.findViewById(R.id.tv_score);
        TextView tv_examinee_name = headerView.findViewById(R.id.tv_examinee_name);
        adapter.addHeaderView(headerView);
        tv_paper_no.setText(tikuBean.getLotNo());
        tv_paper_name.setText(tikuBean.getName());
        tv_time.setText(tikuBean.getTotalTime() + "分钟");
        tv_score.setText(tikuBean.getTotalScore() + "分");
        tv_examinee_name.setText(AppConfig.getInstance().getDisplayName());

        View footerView = getLayoutInflater().inflate(R.layout.item_exam_footer, (ViewGroup) list_paper.getParent(), false);
        footerView.findViewById(R.id.btn_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(self).setTitle("是否交卷？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finishExam(false);
                            }
                        })
                        .setNegativeButton("返回", null).show();
            }
        });
        adapter.addFooterView(footerView, 0);
        list_paper.setAdapter(adapter);
    }

    @Override
    protected void initListeners() {
        tv_back.setOnClickListener(this);
    }

    long secs;

    /**
     * 倒计时
     *
     * @param textView 控件
     * @param waitTime 倒计时总时长
     * @param interval 倒计时的间隔时间
     */
    public void countDown(final TextView textView, long waitTime, long interval) {
        timer = new android.os.CountDownTimer(waitTime, interval) {

            @Override
            public void onTick(long millisUntilFinished) {
                secs = (millisUntilFinished / 1000) - 1;
                textView.setText("剩余时间：" + String.format("%02d:%02d:%02d", (secs % 86400) / 3600, (secs % 3600) / 60, secs % 60));
            }

            @Override
            public void onFinish() {
                finishExam(true);
            }
        };
        timer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void finishExam(boolean isForce) {
        RxKeyboardTool.hideSoftInput(self);
        AnswerBean answerBean = new AnswerBean();
        answerBean.setTikuId(tikuBean.getTikuId());
        endTime = Utils.getCurTimeMills();
        answerBean.setTotalTime((endTime - startTime) / 1000 / 60);
        answerBean.setStartTime(Utils.getCurTimeString(startTime));
        answerBean.setEndTime(Utils.getCurTimeString(endTime));
        answerBean.setUserId(AppConfig.getInstance().getUserId());
        answerBean.setDisplayName(AppConfig.getInstance().getDisplayName());
        answerBean.setPaperNo(tikuBean.getLotNo());
        answerBean.setPaperName(tikuBean.getName());

        List<AnswerJudgmentListBean> answerJudgmentListBeans = new ArrayList<>();
        List<AnswerChoiceListBean> answerChoiceListBeans = new ArrayList<>();

        ChoiceListBean choiceListBean;
        AnswerChoiceListBean answerChoiceListBean;
        List<AnswerItemListBean> answerItemListBeans;
        for (int i = 0; i < adapter.getData().size(); i++) {
            TypeEntity typeEntity = adapter.getData().get(i);
            boolean failed;
            switch (typeEntity.getItemType()) {
                case AppKeyManager.TYPE_JUDGMENT:
                    JudgmentListBean judgmentListBean = (JudgmentListBean) typeEntity;
                    AnswerJudgmentListBean answerJudgmentListBean = new AnswerJudgmentListBean();
                    answerJudgmentListBean.setJudgmentId(judgmentListBean.getItemId());
                    answerJudgmentListBean.setSequ(judgmentListBean.getSequ());
                    int judgmentAnswer = judgmentListBean.getAnswer();
                    if (!isForce && judgmentAnswer == -2) {
                        toast("判断题第" + i + "题没有做，请检查");
                        list_paper.scrollToPosition(i);
                        return;
                    } else if (isForce && judgmentAnswer == -2) {
                        answerJudgmentListBean.setAnswer(judgmentAnswer);
                    } else {
                        answerJudgmentListBean.setAnswer(judgmentListBean.getAnswer());
                    }
                    if (judgmentListBean.getItemAnswer().equals(Integer.toString(judgmentListBean.getAnswer()))) {
                        answerJudgmentListBean.setScore(judgmentListBean.getScore());
                    }
                    answerJudgmentListBeans.add(answerJudgmentListBean);
                    break;
                case AppKeyManager.TYPE_SINGLE_CHOICE:
                    choiceListBean = (ChoiceListBean) typeEntity;
                    answerChoiceListBean = new AnswerChoiceListBean();
                    answerChoiceListBean.setChoiceId(choiceListBean.getItemId());
                    answerChoiceListBean.setSequ(choiceListBean.getSequ());
                    answerChoiceListBean.setType(AppKeyManager.TYPE_SINGLE_CHOICE);
                    answerItemListBeans = new ArrayList<>();
                    failed = false;
                    for (ItemListBean itemListBean : choiceListBean.getItemList()) {
                        AnswerItemListBean answerItemListBean = new AnswerItemListBean();
                        answerItemListBean.setChoiceItemId(itemListBean.getItemId());
                        answerItemListBean.setSequ(itemListBean.getSequ());
                        answerItemListBean.setAnswer(itemListBean.getAnswer());
                        answerItemListBeans.add(answerItemListBean);
                        if (!itemListBean.getItemAnswer().equals(Integer.toString(itemListBean.getAnswer()))) {
                            failed = true;
                        }
                    }
                    if (!failed) {
                        answerChoiceListBean.setScore(choiceListBean.getScore());
                    }
                    if (!isForce) {
                        int count = 0;
                        for (AnswerItemListBean answerItemListBean : answerItemListBeans) {
                            if (answerItemListBean.getAnswer() == 1) {
                                count += 1;
                            }
                        }
                        if (count != 1) {
                            toast("单选题第" + (i - 1) + "题没有做，请检查");
                            list_paper.scrollToPosition(i);
                            return;
                        }
                    }
                    answerChoiceListBean.setItemList(answerItemListBeans);

                    answerChoiceListBeans.add(answerChoiceListBean);
                    break;
                case AppKeyManager.TYPE_MULTIPLE_CHOICE:
                    choiceListBean = (ChoiceListBean) typeEntity;
                    answerChoiceListBean = new AnswerChoiceListBean();
                    answerChoiceListBean.setChoiceId(choiceListBean.getItemId());
                    answerChoiceListBean.setSequ(choiceListBean.getSequ());
                    answerChoiceListBean.setType(AppKeyManager.TYPE_MULTIPLE_CHOICE);
                    answerItemListBeans = new ArrayList<>();
                    failed = false;
                    for (ItemListBean itemListBean : choiceListBean.getItemList()) {
                        AnswerItemListBean answerItemListBean = new AnswerItemListBean();
                        answerItemListBean.setChoiceItemId(itemListBean.getItemId());
                        answerItemListBean.setSequ(itemListBean.getSequ());
                        answerItemListBean.setAnswer(itemListBean.getAnswer());
                        answerItemListBeans.add(answerItemListBean);
                        if (!itemListBean.getItemAnswer().equals(Integer.toString(itemListBean.getAnswer()))) {
                            failed = true;
                        }
                    }
                    if (!failed) {
                        answerChoiceListBean.setScore(choiceListBean.getScore());
                    }
                    if (!isForce) {
                        int count = 0;
                        for (AnswerItemListBean answerItemListBean : answerItemListBeans) {
                            if (answerItemListBean.getAnswer() == 1) {
                                count += 1;
                            }
                        }
                        if (count == 0) {
                            toast("多选题第" + (i - 2) + "题没有做，请检查");
                            list_paper.scrollToPosition(i);
                            return;
                        }
                    }
                    answerChoiceListBean.setItemList(answerItemListBeans);
                    answerChoiceListBeans.add(answerChoiceListBean);
                    break;
            }
        }
        if (answerJudgmentListBeans.size() > 0) {
            answerBean.setJudgmentList(answerJudgmentListBeans);
        }
        if (answerChoiceListBeans.size() > 0) {
            answerBean.setChoiceList(answerChoiceListBeans);
        }

        List<JudgmentListBean> judgmentAnswers = tikuBean.getJudgmentList();
        int judgmentSource = 0;
        for (int i = 0; i < judgmentAnswers.size(); i++) {
            JudgmentListBean judgmentListBean = judgmentAnswers.get(i);
            if (judgmentListBean.getItemAnswer().equals(Integer.toString(judgmentListBean.getAnswer()))) {
                judgmentSource += judgmentListBean.getScore();
            }
        }
        List<ChoiceListBean> choice0Answers = tikuBean.getChoice0List();
        int choice0Source = 0;
        for (int i = 0; i < choice0Answers.size(); i++) {
            ChoiceListBean choiceListBean0 = choice0Answers.get(i);
            boolean failed = false;
            for (int j = 0; j < choiceListBean0.getItemList().size(); j++) {
                if (!choiceListBean0.getItemList().get(j).getItemAnswer().equals(Integer.toString(choiceListBean0.getItemList().get(j).getAnswer()))) {
                    failed = true;
                    break;
                }
            }
            if (!failed) {
                choice0Source += choiceListBean0.getScore();
            }
        }
        List<ChoiceListBean> choice1Answers = tikuBean.getChoice1List();
        int choice1Source = 0;
        for (int i = 0; i < choice1Answers.size(); i++) {
            ChoiceListBean choiceListBean1 = choice1Answers.get(i);
            boolean failed = false;
            for (int j = 0; j < choiceListBean1.getItemList().size(); j++) {
                if (!choiceListBean1.getItemList().get(j).getItemAnswer().equals(Integer.toString(choiceListBean1.getItemList().get(j).getAnswer()))) {
                    failed = true;
                    break;
                }
            }
            if (!failed) {
                choice1Source += choiceListBean1.getScore();
            }
        }

        answerBean.setJudgmentScore(judgmentSource);
        answerBean.setChoice0Score(choice0Source);
        answerBean.setChoice1Score(choice1Source);
        answerBean.setScore(judgmentSource + choice0Source + choice1Source);
        List<SubjectJudgmentListBean> subjectJudgmentList = new ArrayList<>();
        for (JudgmentListBean bean : tikuBean.getJudgmentList()) {
            SubjectJudgmentListBean entity = new SubjectJudgmentListBean();
            entity.setItemId(bean.getItemId());
            entity.setMasterId(bean.getMasterId());
            entity.setJudgmentId(bean.getJudgmentId());
            entity.setSequ(bean.getSequ());
            entity.setScore(bean.getScore());
            subjectJudgmentList.add(entity);
        }
        answerBean.setSubjectJudgmentList(subjectJudgmentList);
        List<SubjectChoiceListBean> subjectChoiceList = new ArrayList<>();
        for (ChoiceListBean bean : tikuBean.getChoice0List()) {
            SubjectChoiceListBean entity = new SubjectChoiceListBean();
            entity.setItemId(bean.getItemId());
            entity.setMasterId(bean.getMasterId());
            entity.setChoiceId(bean.getChoiceId());
            entity.setSequ(bean.getSequ());
            entity.setScore(bean.getScore());
            List<SubjectItemListBean> itemEntities = new ArrayList<>();
            for (ItemListBean itemBean : bean.getItemList()) {
                SubjectItemListBean itemEntity = new SubjectItemListBean();
                itemEntity.setItemId(itemBean.getItemId());
                itemEntity.setMasterId(itemBean.getMasterId());
                itemEntity.setChoiceItemId(itemBean.getChoiceItemId());
                itemEntity.setSequ(itemBean.getSequ());
                itemEntities.add(itemEntity);
            }
            entity.setItemList(itemEntities);
            subjectChoiceList.add(entity);
        }
        answerBean.setSubjectChoiceList(subjectChoiceList);
        for (ChoiceListBean bean : tikuBean.getChoice1List()) {
            SubjectChoiceListBean entity = new SubjectChoiceListBean();
            entity.setItemId(bean.getItemId());
            entity.setMasterId(bean.getMasterId());
            entity.setChoiceId(bean.getChoiceId());
            entity.setSequ(bean.getSequ());
            entity.setScore(bean.getScore());
            List<SubjectItemListBean> itemEntities = new ArrayList<>();
            for (ItemListBean itemBean : bean.getItemList()) {
                SubjectItemListBean itemEntity = new SubjectItemListBean();
                itemEntity.setItemId(itemBean.getItemId());
                itemEntity.setMasterId(itemBean.getMasterId());
                itemEntity.setChoiceItemId(itemBean.getChoiceItemId());
                itemEntity.setSequ(itemBean.getSequ());
                itemEntities.add(itemEntity);
            }
            entity.setItemList(itemEntities);
            subjectChoiceList.add(entity);
        }
        answerBean.setSubjectChoiceList(subjectChoiceList);
        answerBean.setCategory(tikuBean.getCategory());

        answerBeanDao.insert(answerBean);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("已交卷，客观题得分如下");
        builder.setMessage("判断题得分：" + judgmentSource + "分\n" +
                "单选题得分：" + choice0Source + "分\n" +
                "多选题得分：" + choice1Source + "分");
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.create().show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                exit();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                exit();
                return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 确认退出
     */
    private void exit() {
        RxKeyboardTool.hideSoftInput(self);
        new AlertDialog.Builder(this).setTitle("还未完成考试，是否暂存？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tempSave();
                    }
                })
                .setNegativeButton("返回", null).show();
    }

    Observer<Object> observer = new Observer<Object>() {

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(Object value) {

        }

        @Override
        public void onError(Throwable e) {
            if (isFinishing()) {
                return;
            }
            if (mWaitDialog.isShowing()) {
                mWaitDialog.dismiss();
            }
            toast(e.getMessage());
        }

        @Override
        public void onComplete() {
            if (isFinishing()) {
                return;
            }
            if (mWaitDialog.isShowing()) {
                mWaitDialog.dismiss();
            }
            toast("暂存成功");
            finish();
        }
    };

    private void tempSave() {
        if (!mWaitDialog.isShowing()) {
            mWaitDialog.show();
        }
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) {
                try {
                    TempSaveBean tempSaveBean = new TempSaveBean();
                    tempSaveBean.setTikuId(tikuBean.getTikuId());
                    tempSaveBean.setLeftTime(secs);
                    tempSaveBean.setStartTime(startTime);
                    tempSaveBean.setUserId(AppConfig.getInstance().getUserId());

                    List<AnswerJudgmentListBean> answerJudgmentListBeans = new ArrayList<>();
                    List<AnswerChoiceListBean> answerChoiceListBeans = new ArrayList<>();

                    ChoiceListBean choiceListBean;
                    AnswerChoiceListBean answerChoiceListBean;
                    List<AnswerItemListBean> answerItemListBeans;
                    for (int i = 0; i < adapter.getData().size(); i++) {
                        TypeEntity typeEntity = adapter.getData().get(i);
                        switch (typeEntity.getItemType()) {
                            case AppKeyManager.TYPE_JUDGMENT:
                                JudgmentListBean judgmentListBean = (JudgmentListBean) typeEntity;
                                AnswerJudgmentListBean answerJudgmentListBean = new AnswerJudgmentListBean();
                                answerJudgmentListBean.setJudgmentId(judgmentListBean.getItemId());
                                answerJudgmentListBean.setSequ(judgmentListBean.getSequ());
                                int judgmentAnswer = judgmentListBean.getAnswer();
                                if (judgmentAnswer == -2) {
                                    answerJudgmentListBean.setAnswer(judgmentAnswer);
                                } else {
                                    answerJudgmentListBean.setAnswer(judgmentListBean.getAnswer());
                                }
                                answerJudgmentListBeans.add(answerJudgmentListBean);
                                break;
                            case AppKeyManager.TYPE_SINGLE_CHOICE:
                                choiceListBean = (ChoiceListBean) typeEntity;
                                answerChoiceListBean = new AnswerChoiceListBean();
                                answerChoiceListBean.setChoiceId(choiceListBean.getItemId());
                                answerChoiceListBean.setSequ(choiceListBean.getSequ());
                                answerChoiceListBean.setType(AppKeyManager.TYPE_SINGLE_CHOICE);
                                answerItemListBeans = new ArrayList<>();
                                for (ItemListBean itemListBean : choiceListBean.getItemList()) {
                                    AnswerItemListBean answerItemListBean = new AnswerItemListBean();
                                    answerItemListBean.setChoiceItemId(itemListBean.getItemId());
                                    answerItemListBean.setSequ(itemListBean.getSequ());
                                    answerItemListBean.setAnswer(itemListBean.getAnswer());
                                    answerItemListBeans.add(answerItemListBean);
                                }
                                answerChoiceListBean.setItemList(answerItemListBeans);
                                answerChoiceListBeans.add(answerChoiceListBean);
                                break;
                            case AppKeyManager.TYPE_MULTIPLE_CHOICE:
                                choiceListBean = (ChoiceListBean) typeEntity;
                                answerChoiceListBean = new AnswerChoiceListBean();
                                answerChoiceListBean.setChoiceId(choiceListBean.getItemId());
                                answerChoiceListBean.setSequ(choiceListBean.getSequ());
                                answerChoiceListBean.setType(AppKeyManager.TYPE_MULTIPLE_CHOICE);
                                answerItemListBeans = new ArrayList<>();
                                for (ItemListBean itemListBean : choiceListBean.getItemList()) {
                                    AnswerItemListBean answerItemListBean = new AnswerItemListBean();
                                    answerItemListBean.setChoiceItemId(itemListBean.getItemId());
                                    answerItemListBean.setSequ(itemListBean.getSequ());
                                    answerItemListBean.setAnswer(itemListBean.getAnswer());
                                    answerItemListBeans.add(answerItemListBean);
                                }
                                answerChoiceListBean.setItemList(answerItemListBeans);
                                answerChoiceListBeans.add(answerChoiceListBean);
                                break;
                        }
                    }
                    if (answerJudgmentListBeans.size() > 0) {
                        tempSaveBean.setJudgmentList(answerJudgmentListBeans);
                    }
                    if (answerChoiceListBeans.size() > 0) {
                        tempSaveBean.setChoiceList(answerChoiceListBeans);
                    }
                    tempSaveBeanDao.insert(tempSaveBean);
                    emitter.onComplete();
                } catch (Exception e) {
                    emitter.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}
